/*
 * @Author: zhangrui BruceZhang@huayun.com
 * @Date: 2023-07-18 14:22:51
 * @LastEditors: zhangrui BruceZhang@huayun.com
 * @LastEditTime: 2023-07-18 15:25:28
 * @FilePath: \alkaid-rgy\websocket\socket.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package websocket

import (
	"alkaid-rgy/script"
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

var (
	upgrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	close bool = false
)

func OpenSocket() {
	http.HandleFunc("/ws", handleWebSocket)

	go func() {
		err := http.ListenAndServe(":9999", nil)
		if err != nil {
			log.Fatal("ListenAndServe: ", err)
		}

		log.Fatal("开启websokcet")
	}()
}

func handleWebSocket(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("Upgrade:", err)
		return
	}
	defer conn.Close()

	for {
		// 读取客户端发送的消息
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("Read:", err)
			break
		}

		// 处理接收到的消息
		fmt.Printf("Received message: %s\n", string(message))

		// 执行脚本
		script.ExecuteVBSScript("./start.vbs", string(message))

		// 回复客户端消息
		err = conn.WriteMessage(websocket.TextMessage, []byte("true"))
		if err != nil {
			log.Println("Write:", err)
			break
		}

		// 根据某些条件决定关闭WebSocket连接
		if close {
			break
		}
	}
}

func CloseWebSocket() {
	// 根据某些条件判断是否应该关闭WebSocket连接
	// 返回 true 则关闭连接，返回 false 继续保持连接
	close = true
}
